package com.peng.herostory.mq;

import com.alibaba.fastjson.JSONObject;
import com.peng.herostory.rank.RankService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

@Slf4j
public final class MqConsumer {
    private static MqConsumer instance = new MqConsumer();

    private static DefaultMQPushConsumer mqPushConsumer;

    private MqConsumer() {

    }

    public static MqConsumer getInstance() {
        return instance;
    }

    public void init() {
        mqPushConsumer = new DefaultMQPushConsumer("herostory");
        mqPushConsumer.setNamesrvAddr("192.168.221.66:9876");
        try {
            mqPushConsumer.subscribe("addRankScore", "*");
            mqPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                    for (MessageExt messageExt : list) {
                        RankMqMessage message = JSONObject.parseObject(messageExt.getBody(), RankMqMessage.class);
                        log.info(
                                "从消息队列中收到战斗结果, winnerId = {}, loserId = {}",
                                message.getWinnerId(),
                                message.getLoserId()
                        );
                        RankService.getInstance().refreshRankInRedis(message.getWinnerId(), message.getLoserId());
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
            mqPushConsumer.start();
        } catch (Exception e) {
            log.error("e:{0}", e);
        }


    }


}
